#include <utils.h>


/**
 * @brief Return the length of a UTF-16 string in bytes
 *
 * The NULL-terminated character is not counted
 */
static inline gssize
utf16_len(const gunichar2 *str)
{
    register const gunichar2 *p;
    register gssize len = 0;
    for (p = str; *p; ++p)
        ++len;
    return len * 2;
}

GString *
g_string_new_utf16(const gchar *init)
{
    GString *utf16_str;
    gunichar2 *s;
    s = g_utf8_to_utf16(init, -1, NULL, NULL, NULL);
    g_return_val_if_fail(s != NULL, NULL);
    utf16_str = g_string_new_len((gchar *) s, utf16_len(s));
    g_free(s);

    /* Ensure right null-terminated char */
    g_string_append_c(utf16_str, '\0');
    utf16_str->len--;

    return utf16_str;
}

GString *
g_string_truncate_utf16(GString *utf16_str, gsize len)
{
    GString *s;
    s = g_string_truncate(utf16_str, len);
    utf16_str->str[utf16_str->len + 1] = '\0';
    return s;
}

GString *
g_string_append_utf16(GString *utf16_str, const gunichar2 *val)
{
    GString *s;
    s = g_string_append_len(utf16_str, (gchar *) val, utf16_len(val));
    g_string_append_c(utf16_str, '\0');
    utf16_str->len--;
    return s;
}
